<template>
  <div class="main-app">
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="form-inline">
        <el-form-item label="单位名称:">
          <el-input v-model="formInline.name" clearable />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="formInline.isPublish" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="0" />
            <el-option label="已发布" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh-right" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="show-result">

      <!-- 加载动态菜单 -->
      <el-form :inline="true" class="form-inline">
        <el-form-item v-for="item in toolbtn" :key="item.id">
          <el-button type="primary" :icon='item.meta.icon' @click="showViews(item.name)">
            {{ item.meta.title }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="add">
            新增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-edit"
            :disabled="disabled"
            @click="edit"
          >
            编辑
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-view"
            :disabled="disabled"
            @click="view"
          >
            查看详情
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-truck"
            :disabled="disabled"
            @click="car"
          >
            车辆管理
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-s-check"
            :disabled="disabled"
            @click="userInfo"
          >
            用户信息
          </el-button>
        </el-form-item> -->
      </el-form>

      <div class="result" style="margin-top: -10px">
        <el-table ref="multipleTable" v-loading="loading" border :data="tableData" tooltip-effect="dark"
          style="width: 100%" align="center" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="单位名称" width="250" />
          <el-table-column prop="detailedAddress" label="注册地址" width="400" />
          <!-- <el-table-column prop="enterpriseCategoryContent" label="企业类别">
            <template slot-scope="scope">
              <el-tag
                v-for="(item, index) in scope.row.enterpriseCategroyList"
                :key="index"
                size="medium"
              >{{ item }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="epUserName" label="环保负责人" />
          <el-table-column prop="epUserPhone" label="环保负责人手机号" />
          <el-table-column prop="totalInvestment" label="总投资 (万)" />
          <el-table-column label="年产废规模">
            <template slot-scope="scope">
              <el-tag size="medium">{{ scope.row.awpsId | showAwps }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isPublish" label="状态">
            <template slot-scope="scope">
              {{ scope.row.isPublish | showPublishStatus }}
            </template>
          </el-table-column>
          <el-table-column label="使用状态" prop="disabled" width="120">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.disabledColor">{{
            scope.row.disabledName
          }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
        </el-table>
        <div class="page">
          <el-pagination background :current-page.sync="currentPage" layout="total,prev, pager, next, sizes"
            :total="total" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" @current-change="handleCurrentChange"
            @size-change="handleSizeChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    pageMixin
  } from "../../../mixins/index";
  import {
    getList,
    getEnterpriseById
  } from "../../../api/wastecomponey";
  import {
    CompanyCategory,
    AnnualWasteProductionScale,
    CompanyType,
    EquipmentStatus
  } from "../../../utils/resource";
  export default {
    filters: {
      showAwps(value) {
        if (value) {
          var obj = AnnualWasteProductionScale.find((p) => p.value === `${value}`);
          var label = "";
          if (obj) {
            label = obj.label;
          }
          return label;
        }
      },
      showPublishStatus(value) {
        return value === 0 ? "草稿" : "已发布";
      },
    },
    mixins: [pageMixin],
    data() {
      return {
        formInline: {
          name: "",
          isPublish: "",
        },
        form: {},
        toolbtn: [] // 列表顶部按钮
      };
    },
    async created() {
      await this.init();
    },
    methods: {
      // 列表顶部功能按钮点击事件
      showViews(action) {
        //console.log(action);
        switch (action) {
          case '新增':
            this.$router.push("/organization/transport/create");
            break;
          case '编辑':
            if (this.ids.length != 1) {
              this.$message.error('此功能仅限操作1条数据！');
              return;
            }
            this.$router.push(`/organization/transport/edit/${this.id}`);
            break;
          case '查看详情':
            if (this.ids.length != 1) {
              this.$message.error('此功能仅限操作1条数据！');
              return;
            }
            this.$router.push(`/organization/transport/${this.id}/view/${false}`);
            break;
          case '车辆管理':
            if (this.ids.length != 1) {
              this.$message.error('此功能仅限操作1条数据！');
              return;
            }
            this.$router.push(`/organization/transport/car/${this.id}`);
            break;
          case '用户信息':
            if (this.ids.length != 1) {
              this.$message.error('此功能仅限操作1条数据！');
              return;
            }
            this.$router.push(`/organization/transport/user/${this.id}`);
            break;
          case '启用':
            this.DisabledCompany('0');
            break;
          case '禁用':
            this.DisabledCompany('1');
        }
      },
      async DisabledCompany(value) {
        const arr = this.$refs.multipleTable.selection;
        if (arr.length !== 1) {
          this.$message.error('此功能仅限操作1条数据！');
          return;
        }

        let confimText = "";
        if (value === "0") {
          confimText = "启用";
        } else {
          confimText = "禁用";
        }
        this.$confirm(`此操作将所选组织信息状态设置为${confimText}状态, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {

          var formdata = {
            Id: arr[0].id,
            Disabled: parseInt(value)
          };

          // 操作数据
          const {
            success,
            msg
          } = await DisabledCompany(formdata);
          if (success) {
            await this.init();
            this.$message({
              type: "success",
              message: `${confimText}状态更新成功!`,
            });
          } else {
            this.$message({
              type: "error",
              message: msg,
            });
          }

        });
      },
      async reset() {
        this.formInline = {
          name: "",
          isPublish: "",
        };
        await this.init();
      },
      async init() {
        this.tableData = [];
        this.loading = true;
        const {
          data,
          count
        } = await getList({
          limit: this.pageSize,
          page: this.currentPage,
          searchParam: JSON.stringify({
            Name: this.formInline.name,
            IsPublish: this.formInline.isPublish,
            Type: 40,
            AreaNumber: this.$store.state.user.userObj.areaNumberStr,

          }),
        });
        for (const p of data) {
          var obj = EquipmentStatus.find((MM) => MM.value === p.disabled.toString());
          if (obj) {
            p.disabledName = obj.label;
            p.disabledColor = obj.color;
          } else {
            p.disabledName = "无数据";
            p.disabledColor = "red";
          }
          this.tableData.push({
            id: p.id,
            name: p.name,
            detailedAddress: `${p.province} ${p.city} ${p.area} ${p.street} ${p.detailedAddress}`,
            // enterpriseCategroyList: this.showentErpriseCategory(
            //   p.enterpriseCategoryId
            // ),
            epUserName: p.epUserName,
            epUserPhone: p.epUserPhone,
            totalInvestment: p.totalInvestment,
            awpsId: p.awpsId,
            createTime: p.createTime.replace("T", " "),
            isPublish: p.isPublish,
            disabledName: p.disabledName,
            disabledColor: p.disabledColor,
          });
        }
        this.total = count;
        this.loading = false;

        // 初始化按钮数据
        this.toolbtn = JSON.parse(localStorage.getItem('运输单位管理'));
        //console.log(this.toolbtn);
      },
      async getEnterpriseById(id) {
        const {
          data
        } = await getEnterpriseById(id, "1");
        this.form.name = data.name;
        this.form.address = `${data.province} ${data.city} ${data.area}`;
        this.form.detailedAddress = data.detailedAddress;
        this.form.email = data.email;
        this.form.epUserName = data.epUserName;
        this.form.epUserPhone = data.epUserPhone;
        this.form.epTel = data.epTel;
        // this.form.enterpriseCategoryId = this.showentErpriseCategory(
        //   data.enterpriseCategoryId
        // ).toString();
        this.form.enterpriseTypeId = CompanyType.filter(
          (p) => p.value === data.enterpriseTypeId
        )[0].label;
        this.form.unifiedSocialCreditCode = data.unifiedSocialCreditCode;
        this.form.awpsId = AnnualWasteProductionScale.filter(
          (p) => p.value === data.awpsId
        )[0].label;
        this.form.hwblNumber = data.hwblNumber;
        this.form.postalCode = data.postalCode;
        this.form.totalInvestment = data.totalInvestment.toString();
        this.form.legalRepresentativeName = data.legalRepresentativeName;
        this.form.legalRepresentativeTel = data.legalRepresentativeTel;
        this.form.legalRepresentativePhone = data.legalRepresentativePhone;
        this.form.rtcNumber = data.rtcNumber;
      },
      showentErpriseCategory(value) {
        console.log(value);
        const list = [];
        if (value.indexOf(",") > -1) {
          const str = value.split(",");
          for (const p of str) {
            for (const q of CompanyCategory) {
              if (p === q.value) {
                list.push(q.label);
              }
            }
          }
          return list;
        } else {
          const type = CompanyCategory.find((p) => p.value === value)?.label;
          list.push(type);
        }
        return list;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .result {
    margin-top: 10px;
  }

  .show-result {
    margin-top: 10px;
  }

  .abow_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
    overflow: hidden;

    .el-dialog {
      margin: 0 auto !important;
      height: 90%;
      overflow: hidden;

      .el-dialog__body {
        position: absolute;
        left: 0;
        top: 54px;
        bottom: 0;
        right: 0;
        padding: 0;
        z-index: 1;
        overflow: hidden;
        overflow-y: auto;
      }
    }
  }
</style>
